import React from 'react';
import {connect} from 'react-redux'
import {Button, message, Form, Input, Switch, Modal, Select} from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
const {TextArea} = Input;
import {messages} from "share/common";
import CustomerInfoMaintenanceService from 'containers/customer-info-maintenance/customer-info-maintenance.service'
import moment from "moment";
import ListSelector from "components/list-selector";

let deepRecord = {
  enabled: true,
  customerId: "",
  bankName: "",
  bankAccount: "",
  bankNumberName: null,
  bankAccountFlag: "02",
  bankCode: "",
  primaryFlag: false,
  country: "",
  bankAddress: "",
  remark: "",
};
class NewCustomerBank extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      data: [],
      confirmLoading: false,
      record: JSON.parse(JSON.stringify(deepRecord)),
      languageKey: 0,
      showListSelector: false,
      symbols: [],
      id: props.params.id,
    }
  }


  componentWillMount() {
    this.getSymbols();
  }

  componentWillReceiveProps(nextProps) {
    const {languageKey} = this.state;
    if (nextProps.params.visible !== this.props.params.visible && nextProps.params.visible) {
      if (nextProps.params.id) {
        this.setState({
          id: nextProps.params.id,
        });
        this.getBankAccountDetail(nextProps.params.id);
      } else {
        this.props.form.setFieldsValue(deepRecord);
        this.setState({
          id: nextProps.params.id,
          languageKey: languageKey + 1,
          record: JSON.parse(JSON.stringify(deepRecord)),
        });
      }
    }
  }

  getSymbols = () => {
    CustomerInfoMaintenanceService.getSymbols()
      .then(res => {
        this.setState({
          symbols: res.data,
        });
        }
      ).catch(err => {

    })
  };

  //获取客户详情
  getBankAccountDetail = (id) => {
    const {languageKey} = this.state;
    this.setState({
      loading: true,
    });
    CustomerInfoMaintenanceService.getBankAccountDetail(id)
      .then(res => {
        if (res.data.effectiveDate) {
          res.data.effectiveDate = moment(moment(res.data.effectiveDate).utc().format())
        }
        this.props.form.setFieldsValue(res.data);
        this.setState({
          loading: false,
          record: res.data,
          languageKey: languageKey + 1,
        });
      })
      .catch(err => {
        this.setState({
          loading: false,
        });
      })
  };

  onOk = () => {
    const {record} = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if(!record.bankName){
          message.error(messages('customer-info-maintenance.key14')/*银行名称不能为空*/);
          return;
        }
        if(values.primaryFlag){
          this.checkoutPrimaryFlag(values);
        }else{
          this.saveRecord(values);
        }
      }
    });
  };

  checkoutPrimaryFlag = (values) => {
    const {id} = this.state;
    CustomerInfoMaintenanceService.checkoutPrimaryFlag(this.props.params.customerId)
      .then(res => {
          if (res.data.result === "failed") {
            console.log(id)
            if(res.data.primaryAccount.id !== id){
              let title =
                <span>
                <span style={{color: '#2292dd'}}>{res.data.customer.customerName}</span>
                  {messages('financial-management.key308'/*下已有启用的*/)}
                  <span style={{color: '#2292dd'}}>{res.data.primaryAccount.bankName}</span>
                  {messages('financial-management.key309'/*主账户*/)}
                  <span style={{color: '#2292dd'}}>{res.data.primaryAccount.bankAccount}</span>
              </span>;
              let content =
                <span>{messages('financial-management.key310'/*点击【继续】，自动将主账户*/)}
                  <span style={{color: '#2292dd'}}>{res.data.primaryAccount.bankAccount}</span>
                  {messages('financial-management.key311'/*设置为非主账户*/)}
              </span>;
              let that = this;
              Modal.confirm({
                title: title,
                content: content,
                okText: messages('supplier.key67'/*继续*/),
                onOk: () => {
                  that.saveRecord(values)
                },
                onCancel: () => {
                }
              });
            }else{
              this.saveRecord(values);
            }
          } else if (res.data.result === "success") {
            this.saveRecord(values);
          }
        }
      ).catch(err => {

    })
  };

  saveRecord = (values) => {
    const {record} = this.state;
    let params = Object.assign(record, values);
    params.customerId = this.props.params.customerId;
    this.setState({
      confirmLoading: true,
    });
    if (record.id) {
      this.editBankAccount(params);
    } else {
      this.addBankAccount(params);
    }
  };

  addBankAccount = (params) => {
    CustomerInfoMaintenanceService.addBankAccount(params)
      .then(res => {
        this.props.close();
        this.setState({
          confirmLoading: false,
        });
      }
    ).catch(err => {
      this.setState({
        confirmLoading: false,
      });
    })
  };

  editBankAccount = (params) => {
    CustomerInfoMaintenanceService.editBankAccount(params)
      .then(res => {
        this.props.close();
        this.setState({
          confirmLoading: false,
        });
      }
    ).catch(err => {
      this.setState({
        confirmLoading: false,
      });
    })
  };

  onCancel = () => {
    this.props.close();
  };

  //选择银行
  handleChangeBank = (result) => {
    const {record} = this.state;
    if(result.result.length) {
      record.country = result.result[0].countryName;
      record.bankAddress = result.result[0].openAccount;
      record.bankName = result.result[0].bankName;
      record.bankCode = result.result[0].bankCode;
      this.props.form.setFieldsValue({country: result.result[0].countryName, bankAddress: result.result[0].openAccount})
      this.setState({
        record,
      });
    }
    this.setState({
      showListSelector: false,
    });
  };

  changeListSelector = (e, bool) => {
    this.setState({
      showListSelector: bool,
    });
  };
  render() {
    const {record, confirmLoading, languageKey, showListSelector, symbols} = this.state;
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 16}
    };
    return (
      <div>
        <Form>
          <div className="other-icon"/>
          <div>{messages('common.baseInfo')/*基本信息*/}</div>
          <FormItem label={messages('common.column.status'/*状态*/)}{...formItemLayout}>
            {getFieldDecorator('enabled', {
              valuePropName: "checked",
            })(
              <Switch/>
            )}
          </FormItem>
          <FormItem label={messages('financial-management.key315'/*主账户*/)}{...formItemLayout}>
            {getFieldDecorator('primaryFlag', {
              valuePropName: "checked",
            })(
              <Switch/>
            )}
          </FormItem>
          <FormItem label={<span><span style={{color: 'red'}}>*</span>&nbsp;{messages('financial-management.key303'/*银行名称*/)}</span>}
                    {...formItemLayout}>
            <div style={{width: "100%"}} onClick={(e) =>this.changeListSelector(e,true)}>
              <Input placeholder={messages('common.please.select')/* 请选择 */}
                     value={record.bankName}
                     key={languageKey}
                     disabled={!!record.id}/>
            </div>
          </FormItem>
          <FormItem label={messages('financial-management.key318'/*银行户名*/)} {...formItemLayout}>
            {getFieldDecorator('bankNumberName', {
              rules: [{
                required: true,
                message: messages('customer-info-maintenance.key15')/*客户代码不能为空*/
              }]
            })(
              <Input placeholder={messages('common.please.enter')/* 请输入 */} disabled={!!record.id}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout}
                    label={messages('financial-management.key319'/*银行账号*/)} >
            {getFieldDecorator('bankAccount', {
              rules:[
                {
                  required: true,
                  message: messages('common.please.enter')
                },
                {
                  max:50,
                  message: messages('financial-management.key771')/*长度不能超过50*/
                },
                //任务编号 9661 银行账号校验必须包含数字
                {
                  message: messages('financial-management.key320'/*必须包含数字*/),
                  validator: (rule, value, cb) => {
                    if (value === null || value === undefined || value === "") {
                      cb();
                      return;
                    }
                    let regExp = /[0-9]/;
                    //去掉空格
                    value = value.replace(/ /g, '');
                    if (regExp.test(value)) {
                      cb();
                    } else {
                      cb(false);
                    }
                  },
                }
              ]
            })(
              <Input disabled={!!record.id} placeholder={messages('common.please.enter')}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('customer-info-maintenance.key7')/*账户标志*/}>
            {getFieldDecorator('bankAccountFlag', {
            })(
              <Select placeholder={messages('common.please.enter')}>
                {
                  symbols.map(item => {
                    return(
                      <Option key={item.value} value={item.value}>{item.messageKey}</Option>
                    )
                  })
                }
              </Select>
            )}
            <div style={{color: "#999"}}>{messages('customer-info-maintenance.key16')/*个人身份信息开户为对私，公司资质开户为对公，银企直联必需字段*/}</div>
          </FormItem>
          <FormItem {...formItemLayout} label={messages('financial-management.key301'/*国家*/)} >
            {getFieldDecorator('country', {})
            (
              <Input placeholder={messages('common.please.enter')} disabled/>
            )}
          </FormItem>
          <FormItem label={messages('financial-management.key335'/*地址*/)} {...formItemLayout}>
            {getFieldDecorator('bankAddress', {
            })(
              <Input placeholder={messages('common.please.enter')/* 请输入 */}  disabled={!!record.id}/>
            )}
          </FormItem>
          <FormItem label={messages('financial-management.key322'/*备注*/)} {...formItemLayout}>
            {getFieldDecorator('remark', {
            })(
              <TextArea placeholder={messages('common.please.enter')/* 请输入 */}/>
            )}
            <div style={{marginTop: 20}}>
              {messages('financial-management.key323'/*如果没有想要的银行，请联系集团管理员前往*/)}
              {messages('financial-management.key324'/*【银行定义】*/)}
              {messages('common.add')}
            </div>
          </FormItem>
          <div className="slide-footer">
            <Button type="primary" onClick={this.onOk} loading={confirmLoading}>
              {messages('common.save')}
            </Button>
            <Button onClick={this.onCancel}>
              {messages('common.cancel')}
            </Button>
          </div>
        </Form>
        <ListSelector
          visible={showListSelector}
          type="select_bank"
          selectedData={[]}
          onOk={this.handleChangeBank}
          onCancel={(e) =>this.changeListSelector(e,false)}
          single
          extraParams={{isAll: false}}
        />
      </div>
    )
  }
}


NewCustomerBank.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {}
}

const wrappedNewCustomerBank = Form.create()(NewCustomerBank);
export default connect(mapStateToProps)(wrappedNewCustomerBank);
